//
//  MineCollectionViewCell.m
//  CoolFM
//
//  Created by 曹曹 on 16/9/7.
//  Copyright © 2016年 曹曹. All rights reserved.
//

#import "MineCollectionViewCell.h"
#import "CFMacro.h"
#import "RecentCollectionViewCell.h"
#import "FocusCollectionViewCell.h"
#import "DownloadCollectionViewCell.h"
#import "SonglistCollectionViewCell.h"
#import "UIView+Frame.h"
#import "LoginViewController.h"
#import "SettingViewController.h"
#import "GXNetTool.h"
#import "UIImageView+WebCache.h"
#import "LoginDetailViewController.h"
// program model
#import "FocusProgram.h"
#import "FocusProData.h"

#define kRecentCollectionViewCell @"RecentCollectionViewCell"
#define kFocusCollectionViewCell @"FocusCollectionViewCell"
#define kDownloadCollectionViewCell @"DownloadCollectionViewCell"
#define kSonglistCollectionViewCell @"SonglistCollectionViewCell"

@interface MineCollectionViewCell () <UICollectionViewDataSource, UICollectionViewDelegate>
// 昵称
@property (weak, nonatomic) IBOutlet UILabel *userNameLabel;
// 头像
@property (weak, nonatomic) IBOutlet UIImageView *avatarView;
// 描述
@property (weak, nonatomic) IBOutlet UILabel *descriptionLabel;
// 指示线条
@property (weak, nonatomic) IBOutlet UIView *lineView;
// 中间的collectionView
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
// flowlayout
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *layout;
// 按钮视图
@property (weak, nonatomic) IBOutlet UIView *menuView;
// recentButton
@property (weak, nonatomic) IBOutlet UIButton *recentButton;
// 整个用户视图
@property (weak, nonatomic) IBOutlet UIView *userView;
// 视图控制器
@property (nonatomic, strong) UIViewController *rootVC;
// 手势
@property (nonatomic, strong) UIGestureRecognizer *loginTap;
@property (nonatomic, strong) UIGestureRecognizer *detailTap;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *userName750;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *userName751;
// 接收用户信息的字典
@property (nonatomic, strong) NSMutableDictionary *userDic;
// 用户关注model
@property (nonatomic, strong) FocusProgram *program;

@end

@implementation MineCollectionViewCell

// rootVC getter
- (UIViewController *)rootVC {
    id responder = self.nextResponder;
    while (![responder isKindOfClass:[UIViewController class]] && responder != nil) {
        responder = [responder nextResponder];
    }
    return (UIViewController *)responder;
}

#pragma mark - 跳转到设置页面
- (IBAction)setting:(id)sender {
    NSLog(@"push设置页");
    SettingViewController *settingVC = [[SettingViewController alloc] init];
    settingVC.navigationItem.title = @"设置";
    [self.rootVC.navigationController pushViewController:settingVC animated:YES];
}

#pragma mark - 切换collectionViewCell
- (IBAction)changeCollectionViewCell:(id)sender {
    // button.tag = 10, 11, 12, 13
    
    UIButton *button = sender;
    // 更新指示线的位置
    _lineView.gx_centerX = button.gx_centerX;
    //
    for (UIView *view in self.menuView.subviews) {
        if ([view isKindOfClass:[UIButton class]]) {
            UIButton *btn = (UIButton *)view;
            [btn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
            btn.titleLabel.font = [UIFont systemFontOfSize:11];
        }
    }
    [button setTitleColor:kDefaultColor forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:15];
    switch (button.tag) {
        case 10:
            [_collectionView setContentOffset:CGPointMake(0, 0)];
            break;
        case 11:
            [_collectionView setContentOffset:CGPointMake(SCREEN_WIDTH, 0)];
            break;
        case 12:
            [_collectionView setContentOffset:CGPointMake(SCREEN_WIDTH * 2, 0)];
            break;
        case 13:
            [_collectionView setContentOffset:CGPointMake(SCREEN_WIDTH * 3, 0)];
            break;
        default:
            break;
    }
}

#pragma mark - init
- (void)awakeFromNib {
    [super awakeFromNib];
    /**
     * 检测是否登录
     */
    if ([self checkLogin]) {
        /**
         * 修改tap触发事件
         */
        [self addTapDetail];
        /**
         * 登录时给用户信息赋值
         */
        NSDictionary *user_dic = [[NSUserDefaults standardUserDefaults] objectForKey:@"user"];
        _userNameLabel.text = user_dic[@"nickname"];
        [_avatarView sd_setImageWithURL:[NSURL URLWithString:user_dic[@"logo_url"]]
                       placeholderImage:[UIImage imageNamed:kPlacoHolderImage]];
        _avatarView.layer.cornerRadius = 20;
        _avatarView.layer.masksToBounds = YES;
        /**
         * 修改控件位置
         */
        _userName750.priority = 751;
        _userName751.priority = 750;
        _descriptionLabel.hidden = YES;
    } else {
        /**
         * 未登录时, 显示默认的信息
         */
        // 给userView添加登录手势
        [self addTapLogin];
    }
    /**
     * 登录通知
     */
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(logined:)
                                                 name:@"login"
                                               object:@"login"];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(signOff:)
                                                 name:@"signOff"
                                               object:@"signOff"];
    // button的初始设置
    [_recentButton setTitleColor:kDefaultColor forState:UIControlStateNormal];
    _recentButton.titleLabel.font = [UIFont systemFontOfSize:15];
    CGFloat userViewH = 93;
    _layout.itemSize = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT - userViewH - 64 - 49);
    _layout.minimumLineSpacing = 0;
    _layout.minimumInteritemSpacing = 0;
    _layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    // 注册recentCell
    kCollectionViewRegisterNib(@"RecentCollectionViewCell", kRecentCollectionViewCell);
    kCollectionViewRegisterNib(@"FocusCollectionViewCell", kFocusCollectionViewCell);
    kCollectionViewRegisterNib(@"DownloadCollectionViewCell", kDownloadCollectionViewCell);
    kCollectionViewRegisterNib(@"SonglistCollectionViewCell", kSonglistCollectionViewCell);
}
#pragma mark - 收到通知时
- (void)logined:(NSNotification *)noti {
    NSDictionary *userDic = noti.userInfo;
    int error_code = [userDic[@"error_code"] intValue];
    /**
     * 若果登录成功
     */
    if (error_code == 0) {
        NSString *user_ip_url = [NSString stringWithFormat:@"http://api.kufm.cn/v2/user/get_user_info/user_id/%@/user_ip/127.0.0.1", userDic[@"user_id"]];
        NSDictionary *userHeader = @{@"X-SESSION-ID":userDic[@"session_id"],
                                 @"X-APP-ID":kAppID,
                                 @"X-API-ID":@"ios/4.3.0.0.0/appstore/release"
                                 };
        /**
         * 请求用户数据
         */
        [GXNetTool GET:user_ip_url
               andBody:nil
             andHeader:userHeader
           andResponse:GXJSON
       andSuccessBlock:^(id result) {
           NSLog(@"登录成功:%@", result);
           self.userDic = [NSMutableDictionary dictionary];
           [_userDic setObject:result[@"data"][@"app_id"] forKey:@"app_id"];
           [_userDic setObject:result[@"data"][@"is_dj"] forKey:@"is_dj"];
           [_userDic setObject:result[@"data"][@"kugou_id"] forKey:@"kugou_id"];
           if (result[@"data"][@"logo_url"] == nil) {
               [_userDic setObject:@"" forKey:@"logo_url"];
           } else {
               [_userDic setObject:result[@"data"][@"logo_url"] forKey:@"logo_url"];
           }
           [_userDic setObject:result[@"data"][@"nickname"] forKey:@"nickname"];
           [_userDic setObject:result[@"data"][@"sex"] forKey:@"sex"];
           [_userDic setObject:result[@"data"][@"summary"] forKey:@"summary"];
           /**
            * 保存用户信息
            */
           NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
           [user setObject:_userDic forKey:@"user"];
           /**
            * 切换tap手势触发事件
            */
           [self addTapDetail];
           /**
            * 给用户赋值
            */
           _userNameLabel.text = [result[@"data"] objectForKey:@"nickname"];
           [_avatarView sd_setImageWithURL:[NSURL URLWithString:[result[@"data"]objectForKey:@"logo_url"]]
                          placeholderImage:[UIImage imageNamed:kPlacoHolderImage]];
           _avatarView.layer.cornerRadius = 20;
           _avatarView.layer.masksToBounds = YES;
           /**
            * 修改控件位置
            */
           _userName750.priority = 751;
           _userName751.priority = 750;
           _descriptionLabel.hidden = YES;
       } andFailureBlock:^(NSError *error) {
           NSLog(@"失败: %@", error);
       }];
        /**
         * 请求用户关注数据
         */
        NSString *url = @"http://api.kufm.cn/v3/playback/get/record_play/collect";
        NSString *session_id = [[NSUserDefaults standardUserDefaults] objectForKey:@"session_id"];
        NSDictionary *header = @{@"X-USER-ID":@"8839433563981",
                                 @"X-SESSION-ID":session_id};
        NSLog(@"Home----------%@", NSHomeDirectory());
        [GXNetTool GET:url
               andBody:nil
             andHeader:header
           andResponse:GXJSON
       andSuccessBlock:^(id result) {
           NSLog(@"关注节目请求成功:%@", result);
           self.program = [FocusProgram modelWithDictionary:result];
           [self.collectionView reloadData];
       } andFailureBlock:^(NSError *error) {
           NSLog(@"关注节目请求失败");
       }];
    }
}
- (void)signOff:(NSNotification *)noti {
    [self addTapLogin];
    _userNameLabel.text = @"未登录";
    _avatarView.image = [UIImage imageNamed:kPlacoHolderImage];
    /**
     * 修改控件位置
     */
    _userName750.priority = 750;
    _userName751.priority = 751;
    _descriptionLabel.hidden = NO;
}
#pragma mark - 检测是否登录
- (BOOL)checkLogin {
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"user"]) {
        return 1;
    } else {
        return 0;
    }
}
#pragma mark - 转换手势
- (void)addTapDetail {
    [_userView removeGestureRecognizer:_loginTap];
    self.detailTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapToDetail)];
    [_userView addGestureRecognizer:_detailTap];
}
- (void)addTapLogin {
    [_userView removeGestureRecognizer:_detailTap];
    self.loginTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapToLogin)];
    [_userView addGestureRecognizer:_loginTap];
}
#pragma mark - 跳转用户详情页
#warning MineCollectionViewCell send noti
- (void)tapToDetail {
    LoginDetailViewController *loginDetailVC = [[LoginDetailViewController alloc] init];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"hidePlayerView"
                                                        object:@"playerView"
                                                      userInfo:nil];
    
    
    
    
    [self.rootVC.navigationController pushViewController:loginDetailVC animated:YES];
}
#pragma mark - 跳转登录页
- (void)tapToLogin {
    LoginViewController *login = [[LoginViewController alloc] init];
    [self.rootVC.navigationController pushViewController:login animated:YES];
}
#pragma mark - collectionView代理
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    // 四个cell
    return 4;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        RecentCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kRecentCollectionViewCell forIndexPath:indexPath];
        return cell;
    } else if (indexPath.row == 1) {
        FocusCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kFocusCollectionViewCell forIndexPath:indexPath];
        
        cell.focusProgram = _program;
        
        return cell;
    } else if (indexPath.row == 2) {
        DownloadCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kDownloadCollectionViewCell forIndexPath:indexPath];
        return cell;
    } else {
        SonglistCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kSonglistCollectionViewCell forIndexPath:indexPath];
        return cell;
    }
}

@end
